<template>
  <div class="data-filter">
    <div class="filter-list">
      <filter-collapse-panel v-for="(df, idx) in selectedFilters"
                             :key="df.id"
                             :index="idx"
                             :show-time="df.updateAt"
                             :data-filter="df"></filter-collapse-panel>
      <filter-collapse-panel
          v-if="newDataFilter"
          :data-filter="newDataFilter"
          :index="selectedFilters.length"
          :is-new="true"
          :draggable="false"
          :has-feedback="false"
          :removable="true"
      />
      <div ref="addPanelRef" class="flex justify_between" @dragenter="dragEnter">
        <el-select v-model="filterId" size="small" @change="selectFilter"
                   filterable
                   placeholder="添加过滤器">
          <el-option v-for="item in dataFiltersOption"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
        <div class="new-filter-btn px_8 ml_4 mr_2 cursor_point" @click="addFilter">
          <i class="iconfont icon-Add"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, defineComponent, inject, provide, ref } from "vue";
import FilterCollapsePanel from "./filter-collapse-panel.vue";
import { useStore } from "vuex";

export default defineComponent({
  name: "data-filter",
  components: { FilterCollapsePanel },
  setup() {
    const store = useStore();
    const pageFilters = inject("pageFilters");
    const refreshData = inject("refreshData");
    const com = inject("com");
    const components = computed(() => store.state.design.components);
    const subComponents = computed(() => store.state.design.subComponents);
    const newDataFilter = ref(null);
    //  当前组件已选择的过滤器
    const selectedFilters = computed(() => {
      return com.value.dataSource.source.dataFilters.reduce((prev, curr) => {
        const df = pageFilters.value.find(m => m.id == curr.id);
        if (df) {
          prev.push(df);
        }
        return prev;
      }, []);
    });
    const dataFiltersOption = computed(() => {
      console.log(selectedFilters.value);
      const ids = selectedFilters.value.map(item => item.id);
      return pageFilters.value.filter(m => !ids.includes(m.id)).map(item => {
        return {
          label: item.name,
          value: item.id
        };
      });
    });
    // 所有组件使用的过滤器
    const usedFilters = computed(() => {
      const allComps = [...components.value, ...subComponents.value];
      const map = Object.create(null);
      allComps.forEach(com => {
        for (const key in com.dataSource) {
          const ad = com.dataSource[key];
          ad.dataFilters.forEach(m => {
            if (map[m.id]) {
              map[m.id].ids.push(com.id);
              map[m.id].names.push(com.alias);
            } else {
              map[m.id] = {
                ids: [com.id],
                names: [com.alias],
              };
            }
          });
        }
      });
      return map;
    });
    const filterId = ref(null);
    // 选择过滤器
    const selectFilter = () => {
      com.value.dataSource.source.dataFilters.push({ id: filterId.value, enabled: true });
      filterId.value = null;
      refreshData();
    };
    const addFilter = () => {
      if (!newDataFilter.value) {
        newDataFilter.value = {
          id: "0",
          name: "新建过滤器",
          code: "return data;",
          origin: "return data;",
          createAt: "",
          updateAt: "",
        };
      }
    };
    const saveFilter = async (data) => {
      if (data.id !== "0") {
        console.log(data);
        await store.commit("design/UPDATE_FILTER_NAME", data);
        const df = usedFilters.value[data.id];
        if (df) {
          const allComps = [...components.value, ...subComponents.value];
          allComps.forEach(com => {
            for (const key in com.apiData) {
              const ad = com.apiData[key];
              const pf = ad.dataFilters.find(m => m.id === data.id);
              if (pf && pf.enabled) {
                // setDatavData(com.id, key, com.apis[key], ad)
              }
            }
          });
        }
      } else {
        await store.commit("design/CREATE_FILTER", data);
        newDataFilter.value = null;
      }
    };
    const removeFilter = (id) => {
      console.log(id);
      if (id !== "0") {
        com.value.dataSource.source.dataFilters = com.value.dataSource.source.dataFilters.filter(m => m.id !== id);
        console.log(com.value.dataSource.source.dataFilters);
        // refreshData();
      } else {
        newDataFilter.value = null;
      }
    };
    const editFilterName = (val, df) => {
      const newName = val.trim();
      if (newName && df.name !== newName) {
        df.name = newName;
        if (df.id !== "0") {
          store.commit("design/UPDATE_FILTER_NAME", newName);
        }
      }
    };
    const dragEnter = () => {

    };
    provide("usedFilters", usedFilters);
    provide("editFilterName", editFilterName);
    provide("removeFilter", removeFilter);
    provide("saveFilter", saveFilter);
    return {
      pageFilters,
      selectedFilters,
      components,
      subComponents,
      newDataFilter,
      filterId,
      dataFiltersOption,
      refreshData,
      selectFilter,
      addFilter,
      dragEnter,
      removeFilter
    };
  }
});
</script>

<style lang="less" scoped>
@import "./../../../../../style/theme/dark.less";

.data-filter {
  position: relative;
  padding: 10px;
  background: @background-color-1;
  border: @border-color-4;
}

.new-filter-btn {
  border: 1px solid @border-color-3;
}
</style>